﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace SQLServerSyncServer
{
    class UDP
    {
        public UdpClient sender;

        public UDP(string ip, int Port)
        {
            IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse(ip), Port);
            sender = new UdpClient(localIpep);
        }
        public void Send(string message, string remoteIP, int remotePort)
        {
            try
            {
                IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);

                byte[] bytes = Encoding.UTF8.GetBytes(message);
                sender.Send(bytes, bytes.Length, remoteIpep);
                //Log.Message(ref lv, DateTime.Now, "发送:"+message);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void sendBytes(byte[] bytes, string remoteIP, int remotePort)
        {
            try
            {
                IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);

                sender.Send(bytes, bytes.Length, remoteIpep);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void Close()
        {
            sender.Close();
        }
        public void StartListener(ref ListView lv, string ip, int GroupPort)
        {
            bool done = false;
            IPAddress GroupAddress = IPAddress.Parse(ip);
            UdpClient listener = new UdpClient();

            IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

            try
            {
                //IPV6，组播
                //listener.JoinMulticastGroup(GroupAddress);

                //listener.Connect(groupEP);

                while (!done)
                {

                    byte[] bytes = listener.Receive(ref groupEP);

                    Log.Message(ref lv, DateTime.Now, "从" + groupEP.ToString() + " 收到 " + Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }

                listener.Close();

            }
            catch (Exception e)
            {
                Log.Message(ref lv, DateTime.Now, e.Message);
            }

        }
    }
}
